package com.YiYuanDuoXiangShi;

import java.util.Scanner;

public class Polyn {
    //设定初始头指针
    Node head;

    public Polyn() {
        head=new Node();
    }
    public void creatPolyn(){
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入的一元多项式的项数");
        int n=sc.nextInt();
        //系数
        double xishu;
        //指数
        int zhishu;
        for (int i = 0; i < n; i++) {
            Node pre=head;
            Node p=head.next;
            System.out.println("请输入系数");
            xishu=sc.nextDouble();
            System.out.println("请输入指数");
            zhishu=sc.nextInt();
            Node node=new Node(xishu,zhishu);
            while (p!=null&&zhishu>p.zhishu){
                pre=p;
                p=p.next;
            }
            node.next = p;
            pre.next = node;

        }

    }
    public Polyn add(Polyn another){
        Polyn sumPolyn =new Polyn();
        Node p1,p2,pre,p3;
        p1 = this.head.next;
        p2 = another.head.next;
        pre = sumPolyn.head;
        while(p1 != null && p2 != null){
            if (p1.zhishu < p2.zhishu){
                p3 = new Node(p1.xishu,p1.zhishu);
                pre.next = p3;
                pre = p3;
                p1 = p1.next;
            } else if (p1.zhishu > p2.zhishu) {
                p3 = new Node(p2.xishu , p2.zhishu);
                pre.next = p3;
                pre = p3;
                p2 = p2.next;
            }else {
                double sum = p1.xishu + p2.xishu;
                if (Math.abs(sum) < 1e-10){
//                   系数和为零，不插入该项
                    p1 = p1.next;
                    p2 = p2.next;
                }else {
                    p3 = new Node(sum,p1.zhishu);
                    pre.next = p3;
                    pre = p3;
                    p1 = p1.next;
                    p2 = p2.next;
                }
            }
            while(p1!=null){
                p3 = new Node(p1.xishu,p1.zhishu);
                pre.next =p3;
                pre = p3;
                p1 = p1.next;
            }
            while(p2!=null){
                p3 = new Node(p2.xishu,p2.zhishu);
                pre.next =p3;
                pre = p3;
                p2 = p2.next;
            }
        }
        return sumPolyn;
    }
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node p = head.next;
        while (p != null) {
            sb.append(p);
            p = p.next;
            if (p != null)
                sb.append(" + "); // 添加加号，但注意最后一项后不加
        }
        return sb.toString();
    }
}
